<template>
  <div class="sub-out border_style">
    <div class="search">
      <ul>
        <li v-for="(item,index) in tableList" class="border_style text_01"
          :class="`${tableListIndex=== item.index?'current':''}`" @click="getTableList(item,index)">{{item.name}} </li>
      </ul>
      <div class="totallength">共{{page.allTotal||0}}条</div>
      <div class="open-btn">
        <YsButton @click="openModal" class="right-between">新增</YsButton>
      </div>
    </div>
    <proTable class="table-st" :hasPagination="false" :loading="page.tableLoad" :columns="page.columns"
      :data="page.data" @clickPage="onClickPage" :current="pege_param.start_recd" :total="page.allTotal"
      :pageSize="pege_param.limit_recd"></proTable>

    <pro-dialog ref="addFooterForm" width="700" :nopadding="true" :title="`${flawTypeflag?'新增':'编辑'}${formList.title}`">
      <div class="model-box" style="padding: 32px 50px 32px 40px" :class="flawTypeflag?'xinzeng':'bianji'">
        <YsForm ref="yuanxingform" :model="formList" :label-width="200">
          <template v-for="(item,index) in  formList.children">

            <YsRow :gutter="2" v-if="item.type==4">
              <YsCol span="18">
                <YsFormItem :label="item.label" :prop="'children.' + index+'.value1'"
                  :rules="[{required: item.required, message: item.rules_message},item.rules_type=='number'?{type: 'number', message: '请输入数字格式', trigger: 'blur', transform(value) { return Number(value)}}:[]]">
                  <YsInput size="large" :maxlength="item.maxlength" v-model="item.value1"></YsInput>
                </YsFormItem>
              </YsCol>
              <YsCol span="6">
                <YsFormItem class="right-select">
                  <Select class="select-border" size="large" ref="serviceStatusClear1" disabled v-model="item.textVal">
                    <Option v-for="(it, index) in item.children" :value="it.value" :key="index">{{ it.name }}</Option>
                  </Select>
                </YsFormItem>
              </YsCol>
            </YsRow>
            <YsRow :gutter="16" v-if="item.type==1">
              <YsCol span="24">
                <YsFormItem :label="item.label" :prop="'children.' + index+'.value1'"
                  :rules="[{required: item.required, message: item.rules_message},item.rules_type=='number'?{type: 'number', message: '请输入数字格式', trigger: 'blur', transform(value) { return Number(value)}}:[]]">
                  <YsInput size="large" :maxlength="item.maxlength" v-model="item.value1"></YsInput>
                </YsFormItem>
              </YsCol>
            </YsRow>
            <YsRow :gutter="16" v-if="item.type==2">
              <YsCol span="24">
                <YsFormItem :label="item.label" :prop="'children.' + index+'.value1'"
                  :rules="{required: item.required, type:item.rules_type ? item.rules_type: 'number', message: item.rules_message, trigger: 'change'}">
                  <Select class="select-border" ref="serviceStatusClear2" size="large" v-model="item.value1">
                    <Option v-for="(it, index) in item.children" :value="it.value" :key="index">{{ it.name }}</Option>
                  </Select>
                </YsFormItem>
              </YsCol>
            </YsRow>
            <YsRow :gutter="16" v-if="item.type==3">
              <YsCol span="24">
                <YsFormItem :label="item.label">
                  <YsInput size="large" :maxlength="item.maxlength" type="textarea" class="hg100" v-model="item.value1">
                  </YsInput>
                </YsFormItem>
              </YsCol>
            </YsRow>
          </template>
        </YsForm>
        <YsRow class="foot-btn" style="margin-top: 10px">
          <YsButton @click="handleCancel()" size="large">关闭</YsButton>
          <YsButton @click="handleOk('yuanxingform')" :disabled="btnDisabled" size="large" type="primary">确定</YsButton>
        </YsRow>
      </div>
    </pro-dialog>
  </div>
</template>


<script>
import { mapActions, mapState, mapGetters } from "vuex";
import batch from './batch'

export default {
  name: "BuYunXuQueXian",
  computed: {
    ...mapGetters(['getTableRow']) //获取选中行后新增的数据
  },
  data() {
    return {
      ruleState: null,
      btnDisabled: false,
      tableList: {},
      tableListIndex: 0,
      cur_id: null,//编辑用的临时id
      pege_param: {
        rule_id: null, //没有类型
        start_recd: 1, //开始数据
        limit_recd: 14, //查询的条数
      },
      flawTypeflag: true,
      formList: {}, //获取弹出数据
      flCopy: {},
      page: {
        subscribeState: 0,
        tableLoad: false,
        allTotal: 0,
        columns: [],
        data: [],
      },
      fileupload: {},
      app_rule: []
    };
  },
  watch: {
    getTableRow(v) {
      if (v) {
        this.page.data = []
        this.pege_param.rule_id = v.id
        this.ruleState = v.rule_state
        this.pege_param.start_recd = 1
        setTimeout(() => {
          document.getElementsByClassName('ivu-table-body')[2].scrollTop = `${0}px`
        }, 500);
        this.getYuuanXingQueXian();
      }
    }
  },
  mounted() {
    document.getElementsByClassName('ivu-table-body')[2].addEventListener('scroll', this.myScroll);
    this.$nextTick(v => {
      this.getTableList(null, this.tableListIndex)
    })
  },
  created() {
    this.tableList = batch.buttonList
  },
  methods: {
    ...mapActions([
      "setRuleNotFlawSizeAdd", "setRuleNotFlawSizeEdit", "setRuleNotFlawSizeDel", "setRuleNotFlawSizeList",//不计点数缺陷尺寸
      "setCountConversionAdd", "setCountConversionEdit", "setCountConversionDel", "setCountConversionList",//缺陷点数换算
      "setallowCountAdd", "setallowCountEdit", "setallowCountDel", "setallowCountList",//允许缺陷点
      "setTinyDemotionAdd", "setTinyDemotionEdit", "setTinyDemotionDel", "setTinyDemotionList",//微小缺陷降级
      "setotherDemotionAdd", "setotherDemotionEdit", "setotherDemotionDel", "setpageRuleOtherDemotionList",//其他降级
      "setAssignLevelAdd", "setAssignLevelEdit", "setAssignLevelDel", "setAssignLevelList",//指定等级
    ]),
    myScroll() {
      let scrollTop = document.getElementsByClassName('ivu-table-body')[2].scrollTop;
      let clientHeight = document.getElementsByClassName('ivu-table-body')[2].clientHeight;
      let scrollHeight = document.getElementsByClassName('ivu-table-body')[2].scrollHeight;
      if (Math.ceil(scrollTop + clientHeight) >= scrollHeight) {//判断滚动条是否滚动到底部
        setTimeout(() => {
          if (this.page.allTotal == this.page.data.length) return
          this.pege_param.start_recd = this.pege_param.start_recd + 1;
          this.getYuuanXingQueXian();
        }, 500);

      }
    },
    //设置动态列,切换数据
    getTableList(item, idx) {
      this.page.columns = []
      this.page.data = [];
      this.tableListIndex = idx
      this.page.allTotal = 0
      this.pege_param.start_recd = 1
      //弹窗数据
      this.formList = batch.formList[this.tableListIndex]
      //表格数据
      this.page.columns = batch.buttonList[this.tableListIndex].columns
      let flagOne = this.page.columns.find(function (x) { return x.title == '顺序号' })
      if (!flagOne) {
        this.page.columns.unshift({
          title: "顺序号",
          width: 80,
          render: (h, params) => {
            return h('span', params.index + 1)
          }
        })
      }
      let flagTow = this.page.columns.find(function (x) { return x.title == '操作' })
      if (!flagTow) {
        this.page.columns.push({
          title: "操作",
          width: 150,
          // align: "center",
          render: (h, params) => {
            return h(
              "div",
              {
                attrs: { class: "mouse-on" },
              },
              [
                h("span", {
                  // class: ["iconfont", "icon-bianji"],
                  on: {
                    click: (event) => {
                      this.handleEditItem(params.row);
                      event.stopPropagation();
                    },
                  },
                  class: "textColor",
                  // domProps: {
                  //   title: "编辑",
                  // },
                  style: {
                    fontSize: "16px",
                    margin: "0 0 0 8px",
                    display: this.ruleState == 0 ? "inline-block" : "none",
                  },
                }, '编辑'),
                h("span", {
                  domProps: {
                    title: "删除",
                  },
                  // class: ["iconfont", "icon-a-lujing22614"],
                  class: "textColor",
                  on: {
                    click: (event) => {
                      this.handleDlelteItem(params.row);
                      event.stopPropagation();
                    },
                  },
                  style: {
                    fontSize: "16px",
                    margin: "0 0 0 8px",
                    display: this.ruleState == 0 ? "inline-block" : "none",
                  },
                }, '删除'),
              ]
            );
          },
        })
      }
      //验证回复默认
      this.$nextTick(() => {
        this.$refs['yuanxingform'].resetFields();
      })
      //有数据后请求接口
      if (this.pege_param.rule_id) {
        this.getYuuanXingQueXian()
      }
    },
    //获取服务列表
    getYuuanXingQueXian() {
      let _this = this;
      this.page.tableLoad = true;
      this.page.allTotal = 0;
      //1缺陷属性，2-缺陷长径
      if (this.tableListIndex == 5) {
        this.pege_param.assign_class = 1
      } else if (this.tableListIndex == 6) {
        this.pege_param.assign_class = 2
      }
      _this[batch.buttonList[this.tableListIndex].interfaceList](this.pege_param).then((res) => {
        let { data, msg, scode, status } = res;
        _this.page.tableLoad = false;
        if (status === "ok") {
          switch (this.tableListIndex) {
            case 0:
              const old_data0 = JSON.parse(JSON.stringify(this.page.data))
              data.ruleNotFlawSizeInfos = data.ruleNotFlawSizeInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data0.concat(data.ruleNotFlawSizeInfos);
              break;
            case 1:
              const old_data1 = JSON.parse(JSON.stringify(this.page.data))
              data.countConversionInfos = data.countConversionInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data1.concat(data.countConversionInfos);
              // this.page.data = data.countConversionInfos;
              break;
            case 2:
              // this.page.data = data.allowCountInfos;
              const old_data2 = JSON.parse(JSON.stringify(this.page.data))
              data.allowCountInfos = data.allowCountInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data2.concat(data.allowCountInfos);

              break;
            case 3:
              // this.page.data = data.tinyDemotionInfos;
              const old_data3 = JSON.parse(JSON.stringify(this.page.data))
              data.tinyDemotionInfos = data.tinyDemotionInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data3.concat(data.tinyDemotionInfos);
              break;
            case 4:
              const old_data4 = JSON.parse(JSON.stringify(this.page.data))
              data.otherDemotionInfos = data.otherDemotionInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data4.concat(data.otherDemotionInfos);
              // this.page.data = data.otherDemotionInfos
              break;
            case 5:
              // this.page.data = data.assignLevelInfos
              const old_data5 = JSON.parse(JSON.stringify(this.page.data))
              data.assignLevelInfos = data.assignLevelInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data5.concat(data.assignLevelInfos);
              break;
            case 6:
              // this.page.data = data.assignLevelInfos
              const old_data6 = JSON.parse(JSON.stringify(this.page.data))
              data.assignLevelInfos = data.assignLevelInfos.map(v => ({ ...v, remark: v.remark ? v.remark : '--' }))
              this.page.data = old_data6.concat(data.assignLevelInfos);
              break;
            default:
              break;
          }
          this.page.allTotal = data.all_recd;
          this.$forceUpdate()
        } else {
          _this.$YsMessage.error(msg);
        }
      }).catch((err) => {
        _this.page.tableLoad = false;
        _this.$YsMessage.error("获取数据失败");
      });
    },
    //分页
    onClickPage(pageNum) {

      this.pege_param.start_recd = pageNum;
      this.getYuuanXingQueXian();
    },

    //打开模态框
    openModal() {

      if (this.tableListIndex == 6) {
        if (this.page.data.length > 0) {
          this.$YsMessage.info("当前已有数据");
        } else {
          this.formList.children.map((v, index) => {
            v.value1 = ""
            if (v.hasOwnProperty('value2')) {
              v.value2 = ""
            }
            if (v.hasOwnProperty('value3')) {
              v.value3 = ""
            }
          })

          this.$refs.addFooterForm.show()
          this.$refs['yuanxingform'].resetFields();
        }
      } else {
        if (this.pege_param.rule_id) {
          this.formList.children.map((v, index) => {
            v.value1 = ""
            if (v.hasOwnProperty('value2')) {
              v.value2 = ""
            }
            if (v.hasOwnProperty('value3')) {
              v.value3 = ""
            }
          })
          this.$refs['yuanxingform'].resetFields();
          this.$refs.addFooterForm.show()
        } else {
          this.$YsMessage.info("请选择缺陷规则ID");
        }
      }
    },
    //确定
    handleOk(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.getParameters()
        }
      });
    },
    //取消
    handleCancel() {
      this.$refs.addFooterForm.close()
    },
    //获取参数
    getParameters() {
      let parent_parame = {}
      let parame_child = {}
      this.btnDisabled = true
      this.formList.children.map((v, index) => {
        parame_child[v.record] = v.value1
        if (v.value2) {
          parame_child[v.record2] = v.value2
        }
      })

      if (this.tableListIndex == 2) {
        if (parame_child.area_lenght == 1) {
          parame_child.area_lenght = 10
          parame_child.area_width = 10
        } else if (parame_child.area_lenght == 2) {
          parame_child.area_lenght = 20
          parame_child.area_width = 10

        } else if (parame_child.area_lenght == 3) {
          parame_child.area_lenght = 30
          parame_child.area_width = 10
        }
      }
      //1缺陷属性，2-缺陷长径
      if (this.tableListIndex == 5) {
        parame_child.assign_class = 1
      } else if (this.tableListIndex == 6) {
        parame_child.assign_class = 2
      }
      if (!this.flawTypeflag) {
        parame_child.id = this.cur_id
      }
      parame_child.rule_id = this.pege_param.rule_id
      parent_parame[this.formList.parent_record] = parame_child
      if (this.flawTypeflag) {
        this.addYuanXingItem(parent_parame)
      } else {
        this.exitYuanXingItem(parent_parame)
      }

    },
    //新增
    addYuanXingItem(item) {
      let _this = this
      _this[batch.buttonList[this.tableListIndex].interfaceAdd](item).then((res) => {
        let { data, msg, scode, status } = res;
        _this.page.tableLoad = false;
        setTimeout(function () {
          _this.btnDisabled = false
        }, 500)
        if (status === "ok") {
          this.$refs.addFooterForm.close()
          _this.$YsMessage.success(data.message_text)
          _this.page.data = [];
          _this.page.allTotal = 0
          _this.pege_param.start_recd = 1
          _this.getYuuanXingQueXian()
        } else {
          _this.$YsMessage.error(msg);
        }
      }).catch((err) => {
        _this.page.tableLoad = false;
        this.btnDisabled = false
        _this.$YsMessage.error("获取数据失败");
      });
    },
    //编辑
    exitYuanXingItem(item) {
      let _this = this
      _this[batch.buttonList[this.tableListIndex].interfaceEdit](item).then((res) => {
        let { data, msg, scode, status } = res;
        _this.page.tableLoad = false;
        _this.btnDisabled = false
        if (status === "ok") {
          _this.$refs.addFooterForm.close()
          _this.$YsMessage.success(data.message_text)
          _this.page.data = [];
          _this.page.allTotal = 0
          _this.pege_param.start_recd = 1
          _this.getYuuanXingQueXian()
        } else {
          _this.$YsMessage.error(msg);
        }
      }).catch((err) => {
        _this.page.tableLoad = false;
        _this.btnDisabled = false
        _this.$YsMessage.error("获取数据失败");
      });
    },
    //获取圆形表格参数
    handleEditItem(item) {
      this.formList.children.map((v, index) => {
        v.value1 = item[v.record]//值
        if (v.label == "评定区域") {
          if (v.value1 == 10) {
            v.value1 = 1
          }
          if (v.value1 == 20) {
            v.value1 = 2
          }
          if (v.value1 == 30) {
            v.value1 = 3
          }
        }
      })
      this.flawTypeflag = false
      this.cur_id = item.id
      this.$nextTick(() => {
        this.$refs.addFooterForm.show()
      })
    },
    //删除
    handleDlelteItem(item) {
      let _this = this;
      this.$YsModal.confirm({
        title: "删除",
        content: "<p>确认是否删除！</p>",
        onOk: () => {
          let del_param = {}
          del_param[_this.formList.parent_record] = { id: item.id }
          _this[batch.buttonList[this.tableListIndex].interfaceDel](del_param).then((res) => {
            let { data, msg, scode, status } = res;
            if (status === "ok") {
              _this.$YsMessage.success("删除成功");
              _this.page.data = [];
              _this.page.allTotal = 0
              _this.pege_param.start_recd = 1
              _this.getYuuanXingQueXian();
            } else {
              _this.$YsMessage.error(msg);
            }
          }).catch((err) => {
            _this.$YsMessage.error("删除失败");
          });
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  display: flex;
  width: 100%;
  align-items: center;
  padding: 16px 22px 8px;

  .totallength {
    margin-left: 10px;
    min-width: 50px;
  }

  .open-btn {
    margin-left: auto;
  }

  ul {
    display: flex;
    text-align: center;

    li {
      height: 40px;
      line-height: 40px;

      width: 134px;
      border: 1px solid #cfd7e5;
      color: #405680;
      padding: 0 10px;
      border-radius: 4px;
      margin-right: 2px;

      &.current {
        color: #fff !important;
        background-color: #0061ff;
        border-color: #0061ff;
      }

      &:hover {
        cursor: pointer;
        color: #fff !important;
        background-color: #0061ff;
        border-color: #0061ff;
      }
    }
  }
}

/deep/.setAllStyle {
  width: 81px;
  height: 30px;
  line-height: 30px;
  border-radius: 4px;
  text-align: center;
  color: #ffffff;
}

/deep/.right-select {
  .ivu-form-item-content {
    margin-left: 0 !important;
  }
}

.sub-out {
  height: 100% !important;
  border-radius: 0 0 4px 4px;
}

/deep/ .mouse-on {
  .icon-bianji:hover {
    cursor: pointer;
    color: #0091ff;
  }
}

/deep/ .mouse-on {
  .icon-a-lujing22614:hover {
    cursor: pointer;
    color: #d53939;
  }
}

/deep/ .hg100 {
  textarea {
    height: 100px;
  }
}

.ba-table {
  /deep/.ivu-table-wrapper {
    border: none;
  }
}

/deep/ .ivu-table-body {
  height: calc(100% - 59px) !important;
}

.xinzeng {
  /deep/ .ivu-select-item-focus {
    background: transparent !important;
  }
}

/deep/ .textColor {
  // color: '#0091FF';
  cursor: pointer;
  color: #0091ff;

  &:hover {
    opacity: 0.8;
  }
}

.right-between {
  width: 80px;
  min-width: 80px;
  height: 40px;
  background: rgba(255, 255, 255, 0.39);
  border: 1px solid #0061ff;
  opacity: 1;
  border-radius: 4px;
  color: #0091ff;
  font-size: 16px;
  font-family: PingFang SC;
}
</style>
